import { ADMIN_ARTICLE } from '../actionTypes';
import fetch from '../utils/fetch';
import config from '../config';
import { message } from 'antd';
import * as R from 'ramda';

export const update = (payload) => ({
  type: ADMIN_ARTICLE,
  payload,
});

export const updateCategory = (cid) => update({ cid, });
export const updateId = (id) => update({ id, });
export const updateTitle = (title) => update({ title, });
export const updateTop = (top) => update({ top, });
export const updateContent = (content) => update({ content, });

// 获取所有文章
export const getAllArticle = () => async (dispatch, getState) => {
  const res = await fetch({
    method: 'GET',
    url: `${config.host}/api/article/all`,
    headers: {
      // authorization: token,
    }
  }).catch(ex => console.error(ex));
  if (res.code === 200) {
    dispatch(update({ list: res.data }));
  } else {
    message.error('网络服务异常');
  }
};

/**
 * 通过id获取文章
 * @param id
 */
export const getArticleById = (id) => async (dispatch) => {
  if (!id) {
    return false;
  }

  const res = await fetch({
    method: 'GET',
    url: `${config.host}/api/article/${id}`,
  }).catch(ex => console.error(ex));
  if (res.code === 200) {
    const { id, title, cid, content, top } = res.data;
    dispatch(update({
      id,
      title,
      cid,
      content,
      top,
    }));
  } else {
    message.error('网络服务异常');
  }
};

/**
 * 获取首页热点栏目文章列表
 */
export const getHotArticle = () => async (dispatch) => {
  const res = await fetch({
    method: 'GET',
    url: `${config.host}/api/article/category/hot`,
    headers: {
      // authorization: token,
    }
  }).catch(ex => console.error(ex));
  if (res.code === 200) {
    dispatch(update({ hot: res.data }));
  } else {
    message.error('获取热点文章失败');
  }
};

/**
 * 获取所有栏目
 */
export const getCategory = () => async (dispatch, getState) => {
  const res = await fetch({
    method: 'GET',
    url: `${config.host}/api/category/all`,
  }).catch(() => {
    message.error('网络异常');
  });
  if (res.code === 200) {
    const menus = res.data;
    if (!Array.isArray(menus)) {
      return false;
    }
    // 构建父子级关系及排序
    let topMenu = R.compose(
      R.map(item => {
        item.key = item.id;
        item.subMenu = R.compose(
          R.map(item => {
            item.key = item.id;
            return item;
          }),
          R.sort((a, b) => (a.rank - b.rank)),
          R.filter(sub => sub.parent_id && +sub.parent_id === +item.id)
        )(menus);
        return item;
      }),
      R.sort((a, b) => (a.rank - b.rank)),
      R.filter(item => !item.parent_id)
    )(menus);

    let arr = [];
    topMenu.forEach(item => {
      arr.push(item);
      arr = arr.concat(item.subMenu || []);
    });
    dispatch(update({
      category: arr,
    }));
  } else {
    message.error('获取栏目失败');
  }
};

/**
 * 插入图片，上传
 */
export const uploadImg = (param) => async (dispatch, getState) => {
  console.log(param);
  const formData = new FormData();
  formData.append('file', param.file);
  const res = await fetch({
    method: 'post',
    url: `${config.host}/api/upload/content`,
    body: formData,
    headers: {},
  });
  if (res.code === 200) {
    param.success({
      url: res.data,
    })
  } else {
    param.error({
      msg: '上传失败.'
    })
  }
};

/**
 * 新建或编辑文章
 */
export const submit = () => async (dispatch, getState) => {
  const { id = '', cid, title, content, top = 0 } = getState().admin.article;

  if (!cid) {
    message.error('请选择栏目');
    return false;
  } else if (!title) {
    message.error('请填写标题');
    return false;
  } else if (!content) {
    message.error('请填写内容');
    return false;
  }

  const res = await fetch({
    method: 'post',
    url: `${config.host}/api/article/edit`,
    param: {
      id,
      cid,
      title,
      content,
      top,
    },
  }).catch(ex => console.error(ex));
  if (res.code === 200) {
    message.success(id ? '修改成功' : '新增成功');
    dispatch(update({
      id: '',
      cid: '',
      title: '',
      content: '',
      top: 0,
    }));
    location.href = '/#/admin/article';
  } else {
    message.error('网络服务异常');
  }
};

/**
 * 删除文章
 * @param id
 */
export const del = (id) => async (dispatch, getState) => {
  const { list } = getState().admin.article;
  const res = await fetch({
    method: 'post',
    url: `${config.host}/api/article/del`,
    param: {
      id,
    },
  }).catch(ex => console.error(ex));
  if (res.code === 200) {
    const delIndex = list.findIndex(item => item.id === id);
    list.splice(delIndex, 1);
    dispatch(update({ list, }));
    message.success('删除成功');
  } else {
    message.error('网络服务异常');
  }
};

